//
//  QCWKWebViewController.m
//  KDFDApp
//
//  Created by haoran on 17/4/28.
//  Copyright © 2017年 cailiang. All rights reserved.
//

#import "FQBaseWKWebViewController.h"
#import "FQBaseWKWebViewNavigation.h"
#import <WebKit/WKWebView.h>
#import <WebKit/WebKit.h>
#import "FQWKWebView.h"
#import "FQWKWebViewJSHanlder.h"
#import <Masonry.h>
typedef NS_ENUM(NSInteger,wkWebLoadType){
    loadWebURLString = 0,
    loadWebHTMLString,
};
static void *WkwebBrowserContext = &WkwebBrowserContext;

@interface FQBaseWKWebViewController ()<WKUIDelegate,WKNavigationDelegate>

//设置加载进度条
@property (nonatomic,strong) UIProgressView *progressView;
//网页加载的类型
@property(nonatomic,assign) wkWebLoadType loadType;
//保存POST请求体
@property (nonatomic, copy) NSString *postData;
//保存请求链接
@property (nonatomic)NSMutableArray* snapShotsArray;
//webloading过程中显示
@property (nonatomic, assign) BOOL closeCallBack; //是否屏蔽返回事件
@end

@implementation FQBaseWKWebViewController

-(FQBaseWKWebViewNavigation *)navDelegate{
    if (!_navDelegate) {
        _navDelegate = [FQBaseWKWebViewNavigation new];
    }
    return _navDelegate;
}

- (FQWKWebViewJSHanlder *)jsHandler
{
    if (!_jsHandler) {
        _jsHandler = [[FQWKWebViewJSHanlder alloc]init];
    }
    return _jsHandler;
}

- (instancetype)init
{
    if (self = [super init]) {
        self.navDelegate.status = WKWebVCDidLoad;
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(closeCallBack:) name:@"closeCallBack" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(modifyWebTitle:) name:@"modifyWebTitle" object:nil];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.topWebView];
    [self.topWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.mas_topLayoutGuide);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(self.mas_bottomLayoutGuide);
    }];
    [self.view addSubview:_progressView];
    [self webViewloadURLType];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"shakeInvalid" object:nil userInfo:@{@"vc":self}];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self updateNavLeftBar];
    
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"shakeUseful" object:nil userInfo:@{@"vc":self}];
    
    if (self.navigationController.navigationBarHidden) {
        if (@available(iOS 11.0, *)) {
            _topWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
}
- (WKProcessPool *)shareProcessPool
{
    static WKProcessPool  *processPool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        processPool = [[WKProcessPool alloc]init];
    });
    return  processPool;
}

- (FQWKWebView *)topWebView
{
    if (!_topWebView) {
        
        _topWebView = [[FQWKWebView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
        _topWebView.allowsBackForwardNavigationGestures = YES;
        _topWebView.navigationDelegate = self.navDelegate;
        _topWebView.UIDelegate = self.navDelegate;
        _jsHandler.webView = self.topWebView;
        
        _progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, -0.5, CGRectGetWidth(self.view.frame),1)];
        _progressView.trackTintColor = [UIColor whiteColor];
        CGAffineTransform transform = CGAffineTransformMakeScale(1.0f, 0.25f);
        _progressView.transform = transform;
        
        [_topWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];
        [_topWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return _topWebView;
}


#pragma mark ================ 加载方式 ================

- (void)webViewloadURLType{
    switch (self.loadType) {
        case loadWebURLString:{
           
            NSMutableURLRequest * Request_zsj = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.URLString] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:20.0f];
            [self.topWebView loadRequest:Request_zsj];
            break;
        }
        case loadWebHTMLString:{
            [self loadHostPathURL:self.URLString];
            break;
        }
    }
}
- (void)loadHostPathURL:(NSString *)url{
    //获取JS所在的路径
    NSString *path = [[NSBundle mainBundle] pathForResource:url ofType:@"html"];
    //获得html内容
    NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    //加载js
    [self.topWebView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
}

// 调用JS发送POST请求
- (void)postRequestWithJS {
    // 拼装成调用JavaScript的字符串
    NSString *jscript = [NSString stringWithFormat:@"post('%@',{%@});", self.URLString, self.postData];
    // 调用JS代码
    [self.topWebView evaluateJavaScript:jscript completionHandler:^(id object, NSError * _Nullable error) {
    }];
}

- (void)loadWebURLSring:(NSString *)string{
    self.URLString = string;
    self.loadType = loadWebURLString;
//    [self webViewloadURLType];
}

- (void)loadWebHTMLSring:(NSString *)string{
    self.URLString = string;
    self.loadType = loadWebHTMLString;
//    [self webViewloadURLType];
}
#pragma mark - 返回关闭按钮初始化（懒加载）
- (UIBarButtonItem *)closeItem
{
    if (!_closeItem) {
        _closeItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"close"] style:UIBarButtonItemStylePlain target:self action:@selector(closeAction:)];
    }
    return _closeItem;
}

- (UIBarButtonItem *)backItem
{
    if (!_backItem) {
        _backItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"FQ_borrow_arrowleft"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    }
    return _backItem;
}

//点击事件
- (void)backAction:(id)sender
{
    if (_closeCallBack) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"ZYWKWebGobackClick" object:nil];
        return ;
    }
    if ([self.topWebView canGoBack]) {
        [self.topWebView goBack];
    } else {
        self.navigationItem.leftBarButtonItems = nil;
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)closeAction:(id)sender
{
    
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
#pragma mark - 观察者监测进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    //    NSLog(@" %s,change = %@",__FUNCTION__,change);
//    NSLog(@"=======>%@",@(_topWebView.estimatedProgress));
    if ([keyPath isEqual: @"estimatedProgress"] && object == _topWebView) {
        [self.progressView setAlpha:0];
    }
    else if([keyPath isEqualToString:@"title"]&&object == _topWebView) {
        self.navigationItem.title = self.topWebView.title;
    }
    if (_topWebView.estimatedProgress ==1) {
        [self updateNavLeftBar];
        
    }
}

#pragma mark - js注入
- (void)JS_WithArr:(NSArray *)array {

    if (array && [array isKindOfClass:[NSArray class]] && [array count] > 0) {
        [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (obj && [obj isKindOfClass:[NSDictionary class]] && obj[@"host"] && ![obj[@"host"] isEqual:@""]) {
                if ([self.topWebView.URL.host containsString:obj[@"host"]]) {
                    NSString *jsStr = [NSString stringWithFormat:@"(function (src){var script = document.createElement('script');var head = document.getElementsByTagName('head')[0];script.src = src;head.appendChild(script);})('%@');", obj[@"jsfile"] ? : @""];
                    [self.topWebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable rest, NSError * _Nullable error) {
                        
                    }];
                }
            }
        }];
    }
}

- (void)updateNavLeftBar{
    //web 可以返回
    if ([self.topWebView canGoBack]) {
        if (self.navigationController.viewControllers.count > 1) {
            self.navigationItem.leftBarButtonItems = @[self.backItem,self.closeItem];
        }else{
            self.navigationItem.leftBarButtonItems = @[self.backItem];
        }
    }else{
        //web 不可以返回 判断一下导航堆栈是否大于1
        if (self.navigationController.viewControllers.count > 1) {
            self.navigationItem.leftBarButtonItems = @[self.backItem];;
        }else{
            self.navigationItem.leftBarButtonItems = nil;
        }
        
    }
}

#pragma mark - 是否屏蔽返回事件
- (void)closeCallBack:(NSNotification *)notification {
    NSDictionary *dic = notification.object;
    if (dic && dic[@"isShielded"] && [dic[@"isShielded"] isEqual:@"1"]) {
        _closeCallBack = YES;
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
            self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        self.topWebView.allowsBackForwardNavigationGestures = NO;
    }else {
        _closeCallBack = NO;
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
            self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        self.topWebView.allowsBackForwardNavigationGestures = YES;
    }
}

#pragma mark - 修改title
- (void)modifyWebTitle:(NSNotification *)notification {
    NSDictionary *dic = notification.object;
    if (dic && dic[@"nativeTitle"] && ![dic[@"nativeTitle"] isEqual:@""]) {
        self.navigationItem.title = dic[@"nativeTitle"];
    }
}

#pragma mark - 销毁 通过打log形式看webview是否回收
- (void)dealloc{
    _jsHandler.methodMap = nil;
    _jsHandler = nil;
    _navDelegate = nil;
    [_topWebView setUIDelegate:nil];
    [_topWebView setNavigationDelegate:nil];
    [_topWebView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_topWebView removeObserver:self forKeyPath:@"title"];
    _topWebView = nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
